using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WindowsApplication4
{
    public partial class ControlCenter : Form
    {
        public ControlCenter()
        {
            InitializeComponent();
        }

        private void frmMap_Activated(object sender, EventArgs e)
        {
            //this.Activate();

        }

        Map frmMap;
        Map2 frmMap2;
        public ControlCenter(Map frmMap, Map2 frmMap2)
        {
            InitializeComponent();

            this.frmMap = frmMap;
            this.frmMap.Activated += new EventHandler(frmMap_Activated);
            this.frmMap2 = frmMap2;

            this.updownZoom.Value = App.mapZoom;

            this.txtX.Text = App.MapCenter.X.ToString();
            this.txtY.Text = App.MapCenter.Y.ToString();

            this.cbShowNonHighlighted.Checked = App.drawNonSelected;
            this.btnNonHighlightedColor.BackColor = App.nonSelectedColor;

            this.cbShowAbandoned.Checked = App.drawAbondonedVillage;

            frmMap.VillageSelectedEvent += new Map.VillageSelectedDelegate(VillageSelected);

            DataView viewSortedTribes = new DataView(Worlds.currentWorld.dtTribes, World.CONSTS.TribesTable.Columns.IDName + ">0", "tag", DataViewRowState.CurrentRows);


            dgMapHighlights.DataSource = App.dtMapHighlights;

            dgMapHighlights.Columns.Clear();

            DataGridViewComboBoxColumn tribeCol = new DataGridViewComboBoxColumn();
            tribeCol.Name = "tribeID";
            tribeCol.HeaderText = "Tribe";
            tribeCol.DataSource = viewSortedTribes;
            tribeCol.ValueMember = "ID";
            tribeCol.DisplayMember = "tag";
            tribeCol.DataPropertyName = "TribeID";

            dgMapHighlights.Columns.Add(tribeCol);


            DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
            col.Name = "player";
            col.HeaderText = "Player";
            col.DataPropertyName = "PlayerName";
            col.SortMode = DataGridViewColumnSortMode.NotSortable;
            dgMapHighlights.Columns.Add(col);

            DataGridViewButtonColumn butCol = new DataGridViewButtonColumn();
            butCol.Name = "Color";
            butCol.HeaderText = "Color";
            butCol.DataPropertyName = "Color";
            butCol.Width = 50;
            butCol.FlatStyle = FlatStyle.Popup;
            dgMapHighlights.Columns.Add(butCol);

            //dgMapHighlights.DataMember = "MapHighlights";




       }


        private MDIParent1 Parent
        {
            get
            {
                return (MDIParent1)this.MdiParent;
            }
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            if (updownZoom.Value < 1)
            {
                updownZoom.Value = 1;
            }

            App.mapZoom = Convert.ToInt32(updownZoom.Value);

        }

        private void button1_Click(object sender, EventArgs e)
        {
            App.MapCenter = new Point(Convert.ToInt32(txtX.Text), Convert.ToInt32(txtY.Text));
            App.mapZoom = Convert.ToInt32(updownZoom.Value);

            frmMap.RedrawMap();
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void txtX_TextChanged(object sender, EventArgs e)
        {

        }

        private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void ControlCenter_Load(object sender, EventArgs e)
        {

        }

  

        private void btnAdd_Click(object sender, EventArgs e)
        {
        }

        private void dgMapHighlights_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 2 && e.RowIndex > -1)
            {
                DataGridViewButtonCell button = (DataGridViewButtonCell)dgMapHighlights.Rows[e.RowIndex].Cells[2];

                this.colorDialog.Color = button.Style.BackColor;
                if (this.colorDialog.ShowDialog() != DialogResult.Cancel)
                {
                    button.Value = this.colorDialog.Color.ToArgb();                    
                }

            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = "TW++ Saved Settings|*.TWPlus2Save";
           // saveFileDialog1.InitialDirectory = Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments) + @"\TW++ Saved Files";
            
               string serverName = Common.GetServerName(WindowsApplication4.Properties.Settings.Default.Servertype) + ".";

                string worldfolder = "World" + WindowsApplication4.Properties.Settings.Default.world;

                saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\TW++ Saved Files\" + serverName+worldfolder;
            
            if (saveFileDialog1.ShowDialog()  == DialogResult.OK)
            {
                App.dtMapHighlights.WriteXml(saveFileDialog1.FileName);
            }
            

        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "TW++ Saved Settings|*.TWPlus2Save";
          
            string serverName = Common.GetServerName(WindowsApplication4.Properties.Settings.Default.Servertype) + ".";

            string worldfolder = "World" + WindowsApplication4.Properties.Settings.Default.world;

            openFileDialog1.InitialDirectory = Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments) + @"\TW++ Saved Files\"+serverName +worldfolder ;
            openFileDialog1.FileName = "";
            if (openFileDialog1.ShowDialog()  == DialogResult.OK)
            {
                try
                {
                    App.dtMapHighlights.Rows.Clear();

                    // try read
                    DataTable dtTryRead = App.dtMapHighlights.Clone();
                    dtTryRead.ReadXml(openFileDialog1.FileName);
                    ValidateLoadedHighlights(dtTryRead);
                    TextWriter str = new StringWriter();
                    dtTryRead.WriteXml(str);

                    App.dtMapHighlights.ReadXml(new StringReader(str.ToString()));
                }
                catch (Exception)
                {
                    MessageBox.Show("This does not appear to be a valid saved settings file. Setting did no load");
                }
            }
        }

        private void ValidateLoadedHighlights(DataTable dtHighlights)
        {
            List<DataRow> rowsToDelete = new List<DataRow>();
            foreach (DataRow dr in dtHighlights.Rows)
            {
                if (dr[App.CONSTS.MapHighlights.Columns.TribeIDIndex] != DBNull.Value)
                {
                    if (Worlds.currentWorld.GetTribe((int)dr[App.CONSTS.MapHighlights.Columns.TribeIDIndex]) == null)
                    {
                        rowsToDelete.Add(dr);
                    }
                }
                //else if (dr[App.CONSTS.MapHighlights.Columns.PlayerNameIndex] != DBNull.Value)
                //{
                //    if (Worlds.currentWorld.Player((string)dr[App.CONSTS.MapHighlights.Columns.PlayerNameIndex]) == null)
                //    {
                //        rowsToDelete.Add(dr);
                //    }
                //}
            }

            if (rowsToDelete.Count != 0)
            {
                MessageBox.Show("The saved map highlights you are loading contains reference to tribe(s) which no longer exist. Those tribes will not been added to the list of map highlights","Warning",MessageBoxButtons.OK,MessageBoxIcon.Information);
                foreach (DataRow dr in rowsToDelete)
                {
                    dr.Delete();
                }
            }
        }

        private void dgMapHighlights_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == 2)
            {
                if (e.Value != null)
                {
                 
                    if (e.Value != System.DBNull.Value)
                    {

                        DataGridViewButtonCell button = (DataGridViewButtonCell)dgMapHighlights.Rows[e.RowIndex].Cells[2];

                        Color color = Color.FromArgb((int)e.Value);
                        button.Style.BackColor = color;
                        button.Style.SelectionForeColor = color;
                        button.Style.SelectionBackColor = color;
                        button.Style.ForeColor = color;
                    }
                }
            }
        }

        private void dgMapHighlights_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            //if (e.ColumnIndex == 2  && e.RowIndex > 0)
            //{

            //    DataGridViewButtonCell button = (DataGridViewButtonCell)dgMapHighlights.Rows[e.RowIndex].Cells[2];

            //    if (button.Value != null && button.Value != System.DBNull.Value)
            //    {

            //        Color color = Color.FromArgb((int)dgMapHighlights.Rows[e.RowIndex].Cells[2].Value);
            //        button.Style.BackColor = color;
            //        button.Style.SelectionBackColor = color;
            //        button.Style.ForeColor = color;
            //    }


            }

        private void btnNonHighlightedColor_Click(object sender, EventArgs e)
        {
            this.colorDialog.Color = btnNonHighlightedColor.BackColor;
            if (this.colorDialog.ShowDialog() != DialogResult.Cancel)
            {
                btnNonHighlightedColor.BackColor = this.colorDialog.Color;
                App.nonSelectedColor = this.colorDialog.Color;
            }

        }

        private void cbShowNonHighlighted_CheckedChanged(object sender, EventArgs e)
        {
            if (cbShowNonHighlighted.Checked)
            {
                App.drawNonSelected = true;
                btnNonHighlightedColor.Enabled = true;

            }
            else
            {
                App.drawNonSelected = false;
                btnNonHighlightedColor.Enabled = false;
            }

        }

        private void btnShowAbandoned_CheckedChanged(object sender, EventArgs e)
        {
            if (cbShowAbandoned.Checked)
            {
                App.drawAbondonedVillage = true;
            }
            else
            {
                App.drawAbondonedVillage = false;
            }

        }

        public void VillageSelected(Village vill)
        {
//            if (vill != null)
  //          {
    //            label4.Text = vill.ToString();
                villageDisplay.VillageToDisplay = vill;

                if (vill != null)
                {
                    reportDisplay.ReportToDisplay = vill.VillageIntelligence;
                }
                else
                {
                    reportDisplay.ReportToDisplay = null;
                }
               // label4.Text += vill.VillageIntelligence == null ? "" : vill.VillageIntelligence.ReportFrom;
            //}
            //else
            //{
             //   label4.Text = "null";
            //}
        }

        private void dgMapHighlights_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            //if (dgMapHighlights.Rows[e.RowIndex].Cells.Count == 3)
            //{
            //    dgMapHighlights.Rows[e.RowIndex].Cells[2].Value = Color.White.ToArgb();
            //}
        }

        private void btnAddLoad_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "TW++ Saved Settings|*.TWPlus2Save";
           
            string serverName = Common.GetServerName(WindowsApplication4.Properties.Settings.Default.Servertype) + ".";

            string worldfolder = "World" + WindowsApplication4.Properties.Settings.Default.world;

            openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\TW++ Saved Files\" + serverName + worldfolder;
            openFileDialog1.FileName = "";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {

                    // try read
                    DataTable dtTryRead = App.dtMapHighlights.Clone();
                    dtTryRead.ReadXml(openFileDialog1.FileName);
                    ValidateLoadedHighlights(dtTryRead);
                    TextWriter str = new StringWriter();
                    dtTryRead.WriteXml(str);

                    App.dtMapHighlights.ReadXml(new StringReader(str.ToString()));
                    
                }
                catch (Exception)
                {
                    MessageBox.Show("This does not appear to be a valid saved settings file. Setting did no load");
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Clear all map highlights?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                App.dtMapHighlights.Rows.Clear();
                
            }
        }

        private void ControlCenter_FormClosing(object sender, FormClosingEventArgs e)
        {
            WindowsApplication4.Properties.Settings.Default.Save();
        }

        private void btnLeft_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt32( WindowsApplication4.Properties.Settings.Default.centerX ) > 10)
            {
                int i = Convert.ToInt32( WindowsApplication4.Properties.Settings.Default.centerX ) - 10;
                WindowsApplication4.Properties.Settings.Default.centerX = i.ToString();
            }
        }

        private void btnRight_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt32(WindowsApplication4.Properties.Settings.Default.centerX) > 10)
            {
                int i = Convert.ToInt32(WindowsApplication4.Properties.Settings.Default.centerX) + 10;
                WindowsApplication4.Properties.Settings.Default.centerX = i.ToString();
            }

        }

        private void btnTop_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt32(WindowsApplication4.Properties.Settings.Default.centerY) > 10)
            {
                int i = Convert.ToInt32(WindowsApplication4.Properties.Settings.Default.centerY) - 10;
                WindowsApplication4.Properties.Settings.Default.centerY = i.ToString();
            }

        }

        private void btnDown_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt32(WindowsApplication4.Properties.Settings.Default.centerY) > 10)
            {
                int i = Convert.ToInt32(WindowsApplication4.Properties.Settings.Default.centerY) + 10;
                WindowsApplication4.Properties.Settings.Default.centerY = i.ToString();
            }

        }

        private void updownZoom_Scroll(object sender, ScrollEventArgs e)
        {
            
        }

        private void updownZoom_Click(object sender, EventArgs e)
        {
         
        }

        private void updownZoom_MouseClick(object sender, MouseEventArgs e)
        {

        }

        
    }
}